import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class Memory {

    private int[] memory = new int[100];

    private DecimalFormat addressFormat;
    private DecimalFormat valueFormat;
    private AbstractTableModel tableModel;
    private JTable memoryTable;

    public Memory() {
	super();
	memory = new int[100];
	for (int i = 0; i < memory.length; i++) {
	    memory[i] = 0;
	}
	tableModel = new AbstractTableModel() {
	    public int getRowCount() {
		return memory.length;
	    }
	    public int getColumnCount() {
		return 2;
	    }
	    public Object getValueAt(int r, int c) {
		if (c == 0) {
		    return addressFormat.format(r);
		} else {
		    return valueFormat.format(memory[r]);
		}
	    }
	    public String getColumnName(int c) {
		if (c == 0) {
		    return "Addr";
		} else {
		    return "Value";
		}
	    }
	};
	addressFormat = new DecimalFormat("  00");
	valueFormat = new DecimalFormat(" 000");
    }

    public JComponent createVisual() {
	memoryTable = new JTable(tableModel);
	Dimension dim = new Dimension(80, 200);
	memoryTable.setPreferredScrollableViewportSize(dim);
	JScrollPane memoryScrollPane = new JScrollPane(memoryTable,
		JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
		JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
	memoryScrollPane.setBorder(BorderFactory.createTitledBorder("Memory"));
	return memoryScrollPane;
    }

    public void updateDisplay() {
	tableModel.fireTableDataChanged();
    }

    public void load() {
	for (int i = 0; i < memory.length; i++) {
	    memory[i] = 0;
	}
	Iterator iter = LMC.getEditor().getStatements();
	while (iter.hasNext()) {
	    Statement statement = (Statement)iter.next();
	    if (statement.getCodeLength() > 0) {
		int address = statement.getAddress();
		int machineCode = statement.getMachineCode();
		memory[address] = machineCode;
	    }
	}
	memoryTable.setRowSelectionInterval(0,0);
	LMC.getIO().initialize();
	LMC.getCPU().initialize();
	updateDisplay();
    }

    public int get(int addr) {
	return memory[addr];
    }

    public void set(int addr, int val) {
	memory[addr] = val;
    }

}

